<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<!DOCTYPE HTML>
<html lang="zh">
<head>
<%@include file="/WEB-INF/jsp/common/header.jsp"%>
<script src="<%=request.getContextPath()%>/resources/jquery-file-upload/js/vendor/jquery.ui.widget.js" type="text/javascript"></script>
<script src="<%=request.getContextPath()%>/resources/jquery-file-upload/js/jquery.fileupload.js" type="text/javascript"></script>
<style type="text/css">
.addForm {
	width: 80px;
}
.thumbnail{
    width: 100px;
    height: 100px;
}
</style>
<script type="text/javascript">
	var hotelListTable;
	$(document).ready(function() {
		$("#resetForm").click(function() {
			$("#form input").val("");
		});
		$("#save").click(function() {
			var id = $(".modal-body input[name=id]").val();
			var name = $(".modal-body input[name=name]").val();
            var inputPrice = $(".modal-body input[name=inputPrice]").val();
            var remark = $(".modal-body textarea[name=remark]").val();
            var introduction = $(".modal-body textarea[name=introduction]").val();

			if ($.trim(name) === "") {
				$.messager.alert("房间名不能为空");
				return false;
			}
            if (!/^[0-9]+(.[0-9]{1,2})?$/.test(inputPrice)) {
                $.messager.alert("价格不能为空且必须大于0");
                return false;
            }
            if($.trim(introduction) === ""){
                $.messager.alert("房间简介是必填的");
                return false;
            }
            if(introduction.length > 250){
                $.messager.alert("房间简介不能超过 250 个字符");
                return false;
            }
            if(remark.length > 250){
                $.messager.alert("房间描述不能超过 250 个字符");
                return false;
            }
            $('#priceHidden').val((parseFloat(inputPrice) * 100).toFixed(0));
            /*if (!/^[0-9]*[1-9][0-9]*$/.test(quantity)) {
                $.messager.alert("数量不能为空且必须大于0");
                return false;
            }*/
            var valid = true;
            $('#timeArea').find('.form-group').each(function(index, dom){
                var val = $(dom).find('input[name^=timeList]:eq(1)').val();
                if(val === "") valid = false;
            });
            if(!valid){
                $.messager.alert("提示", "预约时间必填");
                return;
            }

			var url = contextpath + "/web/hotel/update";
            if(id === ''){
                url = contextpath + "/web/hotel/insert";
            }
			$(this).attr("disabled","disabled");
			$.ajax({
				type : "POST",
				url : url,
				data : $('#editForm').serialize(),
				success : function(result) {
                    if (result.code === 200) {
                        $("#save").removeAttr("disabled");
                        $("#editModal").modal("hide");
                        $.messager.alert("提示", "保存成功");
                        hotelListTable.ajax.reload(null, false);
                    } else {
                        $.messager.alert("提示", result.msg);
                    }
				}
			});
		});

        //上传图片
        $("#hiddenFileInput").change(function(){
            $('#progress').show();
        });
        //图片上传
        $("#hiddenFileInput").fileupload({
            url : contextpath + '/web/upload/uploadFile',
            dataType: 'json',
            formData : function(form){
                return []
            },
            done: function (e, data) {
                $('#progress').hide();
                var file = data.files[0];
                console.log(data.result);
                if(data.result.code !== 200){
                    $.messager.alert("提示", "图片上传不成功");
                    return;
                }
                $("#hiddenPicInput").val(data.result.data.path);
                $('#picImg').attr('src', data.result.data.server + data.result.data.path);

                $('#progress .progress-bar').css('width', '0%');
            },
            progressall: function (e, data) {
                var progress = parseInt(data.loaded / data.total * 100, 10);
                $('#uploadProgressDlg .progress-percentage').text(data.loaded/1000 + "/" + data.total/1000 + " KB");
                $('#uploadProgressDlg .progress-bar').css('width', progress + '%');
                $('#progress .progress-bar').css('width', progress + '%');
            }
        }).prop('disabled', !$.support.fileInput).parent().addClass($.support.fileInput ? undefined : 'disabled');

        hotelListTable = $('#hotelListTable').DataTable({
            "bSort": true, //是否启动各个字段的排序功能
            "aaSorting": [[4, "desc"]], //默认的排序方式
            "aoColumns": [
                {
                    "mDataProp": "id",
                    "sTitle":"ID",
                    "sDefaultContent": "--",
                    "sWidth": "60",
                    "sClass": "center flow",
                    "bSortable": false,//是否支持排序
                    "bSearchable" : false,//是否支持条件查询
                    "fnCreatedCell": function (nTd, sData, oData, iRow, iCol) {
                        if(sData !== '--') $(nTd).attr('title',sData);
                    }
                },{
                    "mDataProp": "name",
                    "sTitle":"名称",
                    "sDefaultContent": "--",
                    "sWidth": "20%",
                    "sClass": "center flow",
                    "bSortable": false,//是否支持排序
                    "bSearchable" : true,//是否支持条件查询
                    "fnCreatedCell": function (nTd, sData, oData, iRow, iCol) {
                        if(sData !== '--') $(nTd).attr('title',sData);
                    }
                },
                {
                    "mDataProp": "quantity",
                    "sTitle":"房间数量",
                    "sDefaultContent": "--",
                    "sWidth": "10%",
                    "sClass": "center flow",
                    "bSortable": false,//是否支持排序
                    "bSearchable" : false,//是否支持条件查询
                    "fnCreatedCell": function (nTd, sData, oData, iRow, iCol) {
                        if(sData !== '--') $(nTd).attr('title',sData);
                    }
                },
                {
                    "mDataProp": "price",
                    "sTitle":"价格",
                    "sDefaultContent": "--",
                    "sWidth": "10%",
                    "sClass": "center flow",
                    "bSortable": false,//是否支持排序
                    "bSearchable" : false,//是否支持条件查询
                    "fnCreatedCell": function (nTd, sData, oData, iRow, iCol) {
                        if(sData !== '--') $(nTd).html((sData/100).toFixed(2) + "元");
                    }
                },
                {
                    "mDataProp": "createTime",
                    "sTitle": "创建时间",
                    "sWidth": "15%",
                    "sDefaultContent": "--",
                    "bSortable": true,
                    "sClass": "center flow",
                    "bSearchable": false,//是否支持条件查询
                    "fnCreatedCell": function (nTd, sData, oData, iRow, iCol) {
                        if (sData !== '--') $(nTd).attr('title', sData);
                    }
                },
                {
                    "mDataProp": "id",
                    "sTitle": "操作",
                    "sWidth": "120px",
                    "sClass": "center flow",
                    "bSearchable": false,
                    "bSortable": false,
                    "fnCreatedCell": function (nTd, sData, oData, iRow, iCol) {
                        $(nTd).html("<a class='btn btn-xs btn-default' href='javascript:void(0);' onclick='editHotel(" + iRow + ")'><i class='fa fa-pencil'></i>&nbsp;编辑</a>&nbsp;&nbsp;")
                            .append("<a class='btn btn-xs btn-default' href='javascript:void(0);' onclick='deleteHotel(" + iRow + ")'><i class='fa fa-times'></i>&nbsp;删除</a>&nbsp;&nbsp;");
                    }
                }
            ],
            "ajax": {
                url: contextpath + '/web/hotel/queryPage',
                type:"post",
                data: function(data){
                    $.xDataTablesParams(data, $.trim($('#name').val()));
                    return data;
                }
            }
        });

        $('#editModal').on('hide.bs.modal', function () {
            $('#editForm input, #editForm textarea').val('');
            $('#timeArea .template').remove();
        });
    });

    function editHotel(row){
        $('#modalTitle').text('编辑房间信息');
        var rowData = hotelListTable.row(row).data();
        if(!rowData.price) rowData.price = 0;
        $('#editModal :input[name=id]').val(rowData.id);
        $('#editModal :input[name=name]').val(rowData.name);
        $('#editModal :input[name=price]').val(rowData.price);
        $('#editModal :input[name=inputPrice]').val((rowData.price/100).toFixed(2));
        $('#editModal :input[name=remark]').val(rowData.remark);
        $('#editModal :input[name=introduction]').val(rowData.introduction);
        if(!rowData.picUrl || rowData.picUrl === ''){
            $('#picImg').attr('src', '${pageContext.request.contextPath}/resources/img/icon-upload.png');
        }else{
            $('#picImg').attr('src', '${fileViewServer}' + rowData.picUrl);
        }
        if(rowData.timeList) for(var x in rowData.timeList){
            if(x === '0'){
                $('#timeSlotFirst').val(rowData.timeList[x].timeSlot);
                $('#timeSlotFirstId').val(rowData.timeList[x].id);
                continue;
            }
            addTime(rowData.timeList[x]);
        }
        $('#editModal').modal('show');
    }

    function addHotel(){
        $('#modalTitle').text('新增房间信息');
        $('#editModal').modal('show');
    }

    function deleteHotel(row){
        var rowData = hotelListTable.row(row).data();
        $.messager.confirm("确定", "真的要删除'" + rowData.name + "'吗？", function(){
            $.ajax({
               url : contextpath + '/web/hotel/delete/' + rowData.id,
               type : 'DELETE',
               success :  function(data){
                   if (data.code === 200) {
                       $.messager.alert("提示", "删除成功");
                       hotelListTable.ajax.reload();
                   } else {
                       $.messager.alert("提示", data.msg);
                   }
               }
            });
        });
    }

    function searchTable(){
        hotelListTable.ajax.reload();
    }

    /**
     *
     */
    function selectUploadFile(){
        $('#hiddenFileInput').click();
    }

    function removeTimeTemplate(event) {
        $(event.target).parents('.template').remove();
        $('#timeArea').find('.form-group').each(function(index, dom){
            $(dom).find('input[name^=timeList]:eq(0)').attr('name', 'timeList['+ index +'].id');
            $(dom).find('input[name^=timeList]:eq(1)').attr('name', 'timeList['+ index +'].timeSlot');
        });
    }

    function addTime(timeObj){
        var $temp = $('#timeTemplate').clone().removeAttr('id').show();
        if(timeObj){
            $temp.find('input[name^=timeList]:eq(0)').val(timeObj.id);
            $temp.find('input[name^=timeList]:eq(1)').val(timeObj.timeSlot);
        }
        $('#timeArea').append($temp);
        $('#timeArea').find('.form-group').each(function(index, dom){
            $(dom).find('input[name^=timeList]:eq(0)').attr('name', 'timeList['+ index +'].id');
            $(dom).find('input[name^=timeList]:eq(1)').attr('name', 'timeList['+ index +'].timeSlot');
        });
    }
</script>
</head>
<body>
	<div class="container-fluid">
		<div class="sub-header">
			<h2>房间类型列表</h2>
		</div>
		<br/>
		<form id="form" class="form-inline" role="form" action="#" method="post">
			<div class="form-group">
				<div class="input-group">
					<span class="input-group-addon">名称</span>
					<input type="text" class="form-control" id="name" placeholder="名称" style="width: 150px;">
				</div>
			</div>
			<button type="button" class="btn btn-default" onclick="searchTable()">查询</button>
			<button id="add" type="button" class="btn btn-info" onclick="addHotel()">新增房间类型</button>
		</form>
		<br>
		<div>
			<table class="table table-hover table-striped table-bordered" style="table-layout:fixed;" id="hotelListTable"></table>
		</div>
	</div>

	<div class="modal fade" id="editModal" tabindex="-1" role="dialog" aria-hidden="true">
		<div class="modal-dialog modal-lg" style="width: 600px;">
			<div class="modal-content">
				<div class="modal-header">
					<button type="button" class="close" data-dismiss="modal">
						<span aria-hidden="true">&times;</span><span class="sr-only">Close</span>
					</button>
					<h4 class="modal-title" id="modalTitle">房间信息</h4>
				</div>
				<div class="modal-body">
                    <div class="form-group template" style="margin-bottom: 5px; display: none" id="timeTemplate">
                        <div class="input-group">
                            <input type="hidden" name="timeList[0].id">
                            <input type="text" class="form-control auto" name="timeList[0].timeSlot" placeholder="比如：08:30-10:00">
                            <div class="input-group-btn">
                                <a href="javascript:;" onclick="removeTimeTemplate(event)" class="btn btn-success"> <i class="fa fa-minus"></i> </a>
                            </div>
                        </div>
                    </div>
                    <form id="editForm">
                        <input type="hidden" name="id">
                        <table id="editTable" class="table-hover table table-bordered">
                            <tr>
                                <td>
                                    <div class="input-group">
                                        <span class="input-group-addon addForm">名称</span>
                                        <input type="text" class="form-control" name="name" placeholder="名称" style="width: 320px;">
                                    </div>
                                </td>
                            </tr>
                            <tr>
                                <td>
                                    <img id="picImg" src="${pageContext.request.contextPath}/resources/img/icon-upload.png" id="picImg" class="thumbnail" onclick="selectUploadFile()">
                                    <input type="hidden" id="hiddenPicInput" name="picUrl">
                                    <div class="contextual-progress" id="progress" style="display: none;">
                                        <div class="progress">
                                            <div class="progress-bar progress-bar-info" style="width: 0%"></div>
                                        </div>
                                    </div>
                                    <input type="file" id="hiddenFileInput" style="display: none;">
                                </td>
                            </tr>
                            <tr>
                                <td>
                                    <div class="input-group">
                                        <span class="input-group-addon addForm">价格($)</span>
                                        <input type="text" class="form-control" name="inputPrice" placeholder="价格" style="width: 320px;">
                                        <input type="hidden" id="priceHidden" name="price">
                                    </div>
                                </td>
                            </tr>
                            <tr>
                                <td>
                                    <div class="input-group">
                                        <span class="input-group-addon">房间简介</span>
                                        <textarea class="form-control" name="introduction" rows="3" placeholder="房间简介，简单描述"></textarea>
                                    </div>
                                </td>
                            </tr>
                            <tr>
                                <td>
                                    <div class="input-group">
                                        <span class="input-group-addon">房间详情</span>
                                        <textarea class="form-control" name="remark" rows="3" placeholder="房间详情"></textarea>
                                    </div>
                                </td>
                            </tr>
                            <tr id="timeTr">
                                <td>
                                    <p>预约时间段：</p>
                                    <div id="timeArea">
                                        <div class="form-group">
                                            <div class="input-group">
                                                <input type="hidden" id="timeSlotFirstId" name="timeList[0].id">
                                                <input type="text" class="form-control auto" id="timeSlotFirst" name="timeList[0].timeSlot" placeholder="比如：08:30-10:00">
                                                <div class="input-group-btn">
                                                    <a href="javascript:addTime();" class="btn btn-success"> <i class="fa fa-plus"></i> </a>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </td>
                            </tr>
                            <tr>
                                <td align="center">
                                    <button id="save" type="button" class="btn btn-success addForm">保 存</button>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                                    <button id="closeModal" type="button" onclick="$('#editModal').modal('hide');" class="btn btn-danger addForm">关闭</button>
                                </td>
                            </tr>
                        </table>
                    </form>
				</div>
			</div>
		</div>
	</div>


</body>